package com.example.demo01.config;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 自定义拦截器，从请求头中获取语言来决定 Locale 的值
 */
public class MyI18nInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String key = "Language";
        String language = request.getHeader(key);
        if (StringUtils.hasText(language)){
            Locale locale = Locale.forLanguageTag(language);
            // LocaleContextHolder 维护了一个 ThreadLocal<LocaleContext> 用来从 LocaleContext 获取设置的 Locale
            LocaleContextHolder.setLocale(locale);
        }
        return true;
    }
}
